<?php namespace App\Http\Controllers\Api;

use App\CoinLog;
use App\Files;
use App\Http\Services\FileManager;
use App\Http\Services\Tools;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Http\Services\YunPian;
use App\Http\Controllers\Controller;
use App\Images;
use App\User;
use App\UserInfo;
use App\VerifyPhone;
use Carbon\Carbon;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;

class AuthController extends Controller
{

    /**
     * 获取手机验证码
     *
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function getVerifyCodeByPhone(Request $request){

        $phone          = $request->get('phone');
        $isAttact       = VerifyPhone::whereIp($request->ip())->orderBy('created_at', 'desc')->first();
        $isAttact_count = VerifyPhone::whereIp($request->ip())->count();

        if ($isAttact_count > 3 && $isAttact->created_at->timestamp + 60 > time())
            return response()->json(['level'=>'error','message' => '请等待60秒后再发送']);
        if ($isAttact_count > 24 && $isAttact->created_at->timestamp + 60 * 60 * 24 > time())
            return response()->json(['level'=>'error','message' => '不允许访问！']);

        $result = VerifyPhone::wherePhone($phone)->orderBy('created_at', 'desc')->first();
        if ($result && 60 + $result->created_at->timestamp > time())
            return response()->json(['level'=>'error','message' => '请等待60秒后再发送']);

        VerifyPhone::wherePhone($phone)->delete();

        $VerifyCodeByPhone                 = new VerifyPhone();
        $VerifyCodeByPhone->phone          = $phone;
        $VerifyCodeByPhone->verify_code    = sprintf("%04d", rand(1000, 9999));
        $VerifyCodeByPhone->ip             = $request->ip();
        $VerifyCodeByPhone->ensure_session = '';

        $sendSms = new YunPian();
        $sendSms->sendBasicSmsWithCode($phone,"波罗鸡",$VerifyCodeByPhone->verify_code);

        $dataResult = $VerifyCodeByPhone->save();

        return response()->json(['level'=>'success','message'=>trans('验证码发送成功')]);
    }

    public function signUp(Request $request){
        $phone      = $request->get('phone');
        $password   = $request->get('password');
        $nickname   = $request->get('nickname');
        $sex        = $request->get('sex');
        $verifyCode = $request->get('code');

        if(is_null($phone))
            return response()->json(['level'=>'error','message'=>'手机号不能为空！']);

        if(is_null($nickname))
            return response()->json(['level'=>'error','message'=>'昵称不能为空！']);

        if(strlen($password) < 6 || strlen($password) > 20)
            return response()->json(['level'=>'error','message'=>'密码只能6-20位字符！']);

        if(!is_null($phone) && UserManager::isPhoneExists($phone))
            return response()->json(['level'=>'error','message'=>'手机号已存在！']);

        /** @var VerifyPhone $verifyCodeByPhone */
        $verifyCodeByPhone = VerifyPhone::wherePhone($phone)->whereVerifyCode($verifyCode)->first();
        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 < time()){
            return response()->json(['level'=>'error','message' => '验证码不匹配或已过期']);
        }
        $verifyCodeByPhone -> delete();

        $newUser = UserManager::signUp($phone,$password);

        Auth::login($newUser);

        $inviteCode = '';
        $hasOne = true;
        while ($hasOne){
            $inviteCode = Tools::getRandomString(6);
            $hasInviteCode = UserInfo::whereInviteCode($inviteCode)->first();
            if(!$hasInviteCode)
                $hasOne = false;
        }
        $userInfo = new UserInfo();
        $userInfo->user_id     = $newUser->id;
        $userInfo->nickname    = $nickname;
        $userInfo->sex         = $sex;
        $userInfo->invite_code = $inviteCode;
        $userInfo->coin        = 5;
        $userInfo->save();

        $coinLog = new CoinLog();
        $coinLog->coin = 5;
        $coinLog->desc = '注册赠送';
        $coinLog->user_id = $newUser->id;
        $coinLog->save();

        return response()->json(['level'=>'success','message' => '注册成功','data'=>$newUser]);
    }

    /**
     * 用户登录接口
     * @return mixed
     */
    public function signIn(Request $request){
        $phone      = $request->get('phone');
        $password   = $request->get('password');


        if(!UserManager::isPhoneExists($phone))
            return response()->json(['level'=>'error','message'=>'帐号不存在！']);

        if(Auth::attempt(['phone' => $phone , 'password' => $password] , 1)){
            /** @var User $user */
            $user = Auth::user();

            $message = "登录成功";
            $wxUserinfo = Session::get('wx_userinfo');
            if($wxUserinfo && !is_null($wxUserinfo)){
                $user->wechat_openid=$wxUserinfo['openid'];
                $user->save();

                /** @var UserInfo $thatUserInfo */
                $thatUserInfo = UserInfo::whereUserId($user->id)->first();
                if($thatUserInfo){
                    if(is_null($thatUserInfo->nickname))$thatUserInfo->nickname = $wxUserinfo['nickname'];
                    if($thatUserInfo->sex == 0)$thatUserInfo->sex = $wxUserinfo['sex'];
                    if(is_null($thatUserInfo->province))$thatUserInfo->province = $wxUserinfo['province'];
                    if(is_null($thatUserInfo->city))$thatUserInfo->city = $wxUserinfo['city'];
                    if(is_null($thatUserInfo->city))$thatUserInfo->city = $wxUserinfo['city'];

                    /** @var Files $fileModel */
                    $fileModel = FileManager::saveFileByWechatImg($wxUserinfo['head_img']);
                    if($fileModel){
                        $imageModel = Images::whereFileId($fileModel->id)->first();
                        if(!$imageModel){
                            $imageModel = new Images();
                            $imageModel->file_id = $fileModel->id;
                            $imageModel->img_name= 'wechat_img';
                            $imageModel->img_type= $fileModel->file_type;
                            $imageModel->save();

                            $thatUserInfo->photo_id = $imageModel->id;
                        }
                    }

                    $thatUserInfo->save();
                }

                Session::forget('wx_userinfo');

                $message = '登录并绑定微信成功';
            }

            return response()->json(['level'=>'success','message' =>$message,'data'=>$user]);
        }

        return response()->json(['level'=>'error','message'=>'账号或密码错误！']);
    }

    public function loginOut(Guard $guard){
        $guard->logout();

        return redirect()->route('Home.Auth.login');
    }

    public function ResetPassword(Request $request){
        $phone       = $request->get('phone');
        $verify_code = $request->get('code');
        $password    = $request->get('password');

        /** @var User $user */
        $user = User::wherePhone($phone)->first();
        if(!$user)
            return response()->json(['level'=>'error','message'=>'当前账号不存在！']);

        $verifyCodeByPhone = VerifyPhone::wherePhone($phone)->whereVerifyCode($verify_code)->first();
        if(!$verifyCodeByPhone || $verifyCodeByPhone->created_at->timestamp + 60 * 15 <time())
            return response()->json(['level'=>'error','message' => '验证码不匹配或已过期']);

        $verifyCodeByPhone->delete();

        $user->password = bcrypt($password);
        $user->save();
        return response()->json(['level'=>'success','message' => '重置密码成功']);
    }

    public function wechatLogin(Request $request){
        $state = $request->get('state');

        $state = !is_null($state) ? $state : 0;
        $callbackUrl = route('Api.Auth.wechatCallback');
        $url         = WechatLogin::buildRedirectUrl($callbackUrl,$state);
        return redirect($url);
    }

    public function wechatCallback(Request $request){

        $code       = $request->get('code');
        $state      = $request->get('state');

        /** @var  WechatLogin $result */
        $result = WechatLogin::getWechatUserInfo($code);

        $accessToken = $result->getAccessToken();
        $openId      = $result->getOpenId();
        $nickname    = $result->getNickname();
        $sex         = $result->getSex();
        $headImgUrl  = $result->getHeadimgurl();
        $province    = $result->getProvince();
        $city        = $result->getCity();
        $unionid     = $result->getUnionid();

        /** @var User $userModel */
        $userModel = User::whereWechatOpenid($openId)->first();

        if(!$userModel){
            $wechatUserInfo = array(
                'openid' => $openId,
                'nickname' => $nickname,
                'sex'      => $sex,
                'head_img' => $headImgUrl,
                'province' => $province,
                'city'     => $city
            );
            Session::put('wx_userinfo',$wechatUserInfo);
            return redirect(route('Home.Auth.login'));
        }else{
            Auth::login($userModel, 1);
            return redirect('http://boluoji.rzkeji.com/newGoodsDetail?id=7');
        }
    }

    public function updateCode(){
        $a = shell_exec("cd /var/www/ && ./update_code.sh 2>&1");
        echo '<pre>';
        print_r($a);
        echo '</pre>';
    }
}